package com.zwcl.common.component.upload.service;

import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.auth.COSSigner;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.region.Region;
import com.zwcl.common.component.upload.cloud.OSSFactory;
import com.zwcl.common.component.upload.config.TencentCosConfig;
import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.exception.BaseException;
import com.zwcl.common.core.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

//TODO:这个文件没有自动装载，一定设置为自动装载，依赖处的项目，必须要要进行相关的yml配置
//上传图片到腾讯云COS
@Slf4j
@Component
public class UploadTencentCos {
    //全部找运维设定好
//    public static final String secretId="AKIDHRPDqIOErMgdP4pt55uYqxtdERTKGVq0";
//    public static final String secretKey="75bv9B4mJeQ2TjpnW7XpvqZDk6HH1b1J";
//    public static final String region="ap-shanghai";
//    public static final String bucketName = "etc-complaint-1259440055";
//    public static final String upHost="https://etc-complaint-1259440055.cos.ap-shanghai.myqcloud.com";
    @Autowired
    TencentCosConfig tencentCosConfig;


    @Autowired
    private OSSFactory ossFactory;

//    @Value("${upload.tencent.secretId}")
//    private String secretId;
//    @Value("${upload.tencent.secretKey}")
//    private String secretKey;
//    @Value("${upload.tencent.region}")
//    private String region;
//    @Value("${upload.tencent.bucketName}")
//    private String bucketName;
//    @Value("${upload.tencent.upHost}")
//    private String upHost;

    /**
     * 获取腾讯云上传文件的签名等Json信息
     * 然后由客户端上传
     * @param folderPath
     * @return
     */
    public JSONObject getUploadUrl(String folderPath){
        // 1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getSecretId(), tencentCosConfig.getSecretKey());
        // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(tencentCosConfig.getRegion()));
        // 3 生成 cos 客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名需包含appid
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String sCurDate = sdf.format(d);
        String key = "/"+folderPath+"/"+sCurDate+"/"+ MD5Utils.getMd5(UUID.randomUUID().toString());
        //String key = "/"+MD5Utils.getMd5(UUID.randomUUID().toString());
        Date expiredTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
        // 生成预签名上传 URL
        //URL url = cosclient.generatePresignedUrl(bucketName, key, expiredTime, HttpMethodName.POST);
        //String uploadUrl= url.toString().replace("http:","https:");
        COSSigner signer = new COSSigner();
        // 要签名的 key, 生成的签名只能用于对应此 key 的上传
        String sign = signer.buildAuthorizationStr(HttpMethodName.POST, key, cred, expiredTime);
        String url=String.format("%s%s",tencentCosConfig.getUpHost(),key);
        log.info("签名：{}",sign);
        JSONObject ret = new JSONObject();
        log.info("签名Url：{}",url.toString());
        ret.put("file_url", url);
        ret.put("file_name", key);
        ret.put("sign",sign);
        return ret;
    }

    /**
     * 上传文件，直接流式文件上传到java后端，由后端上传云
     * 阿里云，七牛云上传文件；腾讯云暂时没有处理好
     * @param file
     * @return
     * @throws Exception
     */
    public String upload( MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BaseException("上传文件不能为空");
        }
        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = ossFactory.build().uploadSuffix(file.getBytes(), suffix);
        return url;
    }

}
